package midoo.server.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.json.simple.JSONValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * Created by jz on 2014/6/24.
 *
 */

public class NetStringsEncoder extends MessageToByteEncoder<Object> {
    private static final Logger LOGGER = LoggerFactory.getLogger(NetStringsEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        Map jmsg = (Map) msg;

        String jsonString = JSONValue.toJSONString(jmsg);
        String msgStr = "" + jsonString.length() + ":" + jsonString  + ',';

//        LOGGER.info("NetStringsEncoder to {}:{}", ctx.channel().remoteAddress(), msgStr);

        out.writeBytes(msgStr.getBytes());
    }
}
